<template>
  <div>
    <public-modal
      width="550px"
      :footer="false"
      :title="title"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="cancel"
    >
      <div slot="content" class="form-wrapper">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          class="form-table-style"
          autocomplete="off"
          layout="inline"
          labelAlign="left"
          :labelCol="{ style: 'width: 100px' }"
        >
          <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="角色类型" prop="roleType" :colon="false">
                <a-select allowClear v-model="form.roleType" placeholder="请选择">
                  <a-select-option :value="item.value" v-for="(item, index) in roleTypeList" :key="index">
                    {{ item.text }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>

            <!--  <a-col flex="1">
              <a-form-model-item label="状态" prop="isActive" :colon="false">
                <a-select allowClear v-model="form.isActive" placeholder="请选择">
                  <a-select-option :value="item.value" v-for="(item, index) in isActiveList" :key="index">
                    {{ item.text }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col> -->
          </a-row>
          <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="成员姓名" prop="memberName" :colon="false">
                <a-input autocomplete="off" placeholder="请填写" v-model="form.memberName" />
              </a-form-model-item>
            </a-col>
            <a-col flex="1">
              <a-form-model-item label="性别" prop="sex" :colon="false">
                <a-select allowClear v-model="form.sex" placeholder="请选择">
                  <a-select-option :value="item.value" v-for="(item, index) in sexList" :key="index">
                    {{ item.text }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!--   <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="家庭类型" prop="familyType" :colon="false">
                <a-select allowClear v-model="form.familyType" placeholder="请选择">
                  <a-select-option :value="item.value" v-for="(item, index) in familyTypeList" :key="index">
                    {{ item.text }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row> -->
          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="联系电话" prop="phone" :colon="false">
                <a-input :maxLength="11" autocomplete="off" placeholder="请填写" v-model="form.phone" />
              </a-form-model-item>
            </a-col>
            <a-col flex="auto">
              <a-form-model-item label="身份证" :colon="false" prop="idCard">
                <a-input :maxLength="30" autocomplete="off" placeholder="请填写" v-model="form.idCard" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="现居地址" prop="address" :colon="false">
                <a-input autocomplete="off" placeholder="请填写" v-model="form.address" />
              </a-form-model-item>
            </a-col>
            <a-col flex="1">
              <a-form-model-item label="家庭住址" prop="homeAddress" :colon="false">
                <a-input autocomplete="off" placeholder="请填写" v-model="form.homeAddress" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="经度" :colon="false">
                <a-input autocomplete="off" placeholder="请填写" v-model="form.longitude" />
              </a-form-model-item>
            </a-col>
            <a-col flex="1">
              <a-form-model-item label="纬度" :colon="false">
                <a-input autocomplete="off" placeholder="请填写" v-model="form.latitude" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row type="flex">
            <a-col flex="1">
              <a-form-model-item label="备注" :colon="false">
                <a-input autocomplete="off" placeholder="请填写" v-model="form.remark" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div slot="footer" v-if="!['add', 'edit'].includes(actionType)"></div>
    </public-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/api'
import { checkIDCard } from '@/utils/validate.js'
import publicModal from '@/components/publicModal'
import { putAction, postAction } from '@/api/manage'
import { isMobile } from '@/utils/validate'
import { getDictItemsFromCache, ajaxGetDictItems } from '@/api/api'
import { getPrefixImg, previewImage } from '@/utils/util'
import moment from 'moment'
import { getFileAccessHttpUrl } from '../../../../api/manage'

export default {
  name: 'addPatientModal',
  components: { publicModal },
  props: {
    tid: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      title: '新增',
      record: {},
      status: 0,
      publicVisible: false,
      imageUrl: [],
      sexList: getDictItemsFromCache('sex_type'),
      roleTypeList: [],
      isActiveList: [],

      showUploadList: { showPreviewIcon: false },
      form: {},
      rules: {
        memberName: [{ required: true, message: '请填写!' }],
        sex: [{ required: true, message: '请选择!' }],
        // familyType: [{ required: true, message: '请选择!' }],
        phone: [{ required: true, message: '请填写!' }],
        idCard: [
          { required: true, message: '请输入身份证号!' },
          {
            validator: (rule, value, callback) => {
              if (!checkIDCard(value)) {
                callback(new Error('请输入正确的身份证号'))
              } else {
                callback()
              }
            },
          },
        ],

        roleType: [{ required: true, message: '请选择!' }],
        isActive: [{ required: true, message: '请选择' }],
        address: [{ required: true, message: '请填写!' }],
        homeAddress: [{ required: true, message: '请填写!' }],

        /*   */
      },
      // politicalList: getDictItemsFromCache('political_outlook'),
      // nationList: getDictItemsFromCache('nation'),

      // sexList: getDictItemsFromCache('sex_type'),
      actionType: '',
      uploadImgRef: null,
      imgPrefix: getPrefixImg(),
      parentStatusList: [],
      familyTypeList: [],
      SocialAssistanceList: [],
      housingPropertyList: [],
      economicAssessmentList: [],
      familyAtmosphereList: [],
      parchiRelationList: [],
    }
  },
  inject: ['provideData'],
  mounted() {
    this.fetchDictData()
  },
  methods: {
    async fetchDictData() {
      try {
        const [roleRes, familyRes, housingRes, economicRes, familyAtmoRes, qinziRes] = await Promise.all([
          ajaxGetDictItems({ code: 'caregroup_role' }),
          // ajaxGetDictItems({ code: 'family_type' }),
          // ajaxGetDictItems({ code: 'enjoy_social_assistance' }),
          // ajaxGetDictItems({ code: 'housing_property' }),
          // ajaxGetDictItems({ code: 'economic_assessment' }),
          // ajaxGetDictItems({ code: 'family_atmosphere' }),
          // ajaxGetDictItems({ code: 'parent_child_relationship' }),
          // 确保使用不同code
        ])

        this.roleTypeList = roleRes.result
        this.familyTypeList = familyRes.result
        //  this.isActiveList = activeRes.result
        this.housingPropertyList = housingRes.result
        this.economicAssessmentList = economicRes.result
        this.familyAtmosphereList = familyAtmoRes.result
        this.parchiRelationList = qinziRes.result
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },

    async show(record = {}, actionType = 'add') {
      this.actionType = actionType
      this.record = record
      this.publicVisible = true
      console.log('编辑模式下record', record)

      if (actionType == 'edit') {
        this.title = `编辑关爱人员`
        this.form = { ...record, sex: String(this.record.sex), roleType: String(this.record.roleType) }
        console.log(this.form)
        if (record.userImg) {
          const obj = {
            uid: record.userImg,
            name: record.userImg,
            status: 'done',
            url: this.imgPrefix + record.userImg,
          }
          this.fileList = [obj]
          this.imageUrl = [{ halfPath: record.userImg }]
        }
      } else if (actionType == 'add') {
        this.title = `新增关爱人员`
        this.$set(this.form, 'minorId', this.tid)
      } else {
        this.title = `关爱人员详情`
        this.form = { ...record, sex: String(this.record.sex), roleType: String(this.record.roleType) }
      }
    },

    remove(file) {
      console.log('remove')
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })
      this.fileList.splice(index, 1)
      this.imageUrl.splice(index, 1)
      // 上传完成之后，隐藏上传框
      let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
      uploadDom.style.display = 'flex'
    },
    async customRequest(info) {
      console.log(info, '上传')
      let file = info.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 2)
      let res = await uploadFile(formData)
      if (res.code == 200) {
        this.imageUrl = [res.result]
        //this.imageUrl.push(res.result.halfPath)
        this.form.imageUrl = [res.result.halfPath]
        this.fileList = [res.result].map((item, index) => {
          return {
            uid: index,
            status: 'done',
            url: item.fullPath,
          }
        })

        // 上传完成之后，隐藏上传框
        let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
        uploadDom.style.display = 'none !important'
      }
    },
    uploadChange({ file, fileList }) {
      file.status = 'done'
      this.fileList = fileList
    },

    handleOk() {
      console.log('dianjiqueding ', this.tid)
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        let url = ''
        if (this.actionType == 'add') {
          url = '/qnMinorCareTeam/addMinorCareTeam'
        } else {
          url = '/qnMinorCareTeam/updateMinorCareTeam'
        }
        const method = this.tid ? postAction : postAction
        try {
          const res = await method(url, {
            ...this.form,
            minorId: this.tid,
          })
          this.$message.success(res.message)
          this.$emit('refresh')
          this.cancel()
        } catch (error) {
          // 处理错误
          console.error('请求失败:', error)
          this.$message.error('请求失败，请稍后重试！')
        }
      })
    },
    handleAdd() {
      this.$refs.addRef.show()
    },

    cancel() {
      this.publicVisible = false
      this.fileList = []
      this.imageUrl = []
      this.form = {}
    },
    handlePreview(urls = []) {
      urls = urls.map((item) => item.halfPath)
      previewImage.call(this, urls)
    },
  },
}
</script>

<style scoped lang="less">
.form-row {
  display: flex;

  flex-wrap: nowrap; /* 禁止换行 */

  align-items: flex-start; /* 顶部对齐 */
}
.picture.ant-col {
  display: flex;
  /deep/ .ant-form-item-label {
    height: 195px !important;
    border-right: none !important;
    line-height: 195px;
    text-align: center;
  }
}
.formStyle {
  padding: 0.2rem;
  /deep/.ant-col {
    height: unset;
  }
  .ant-form-inline .ant-form-item-with-help {
    margin-bottom: 5px;
  }
}
.form-wrapper {
  padding: 32px 25px 20px 25px;
  /deep/.avatar-uploader {
    height: 188px;
    width: 192px;

    .ant-upload {
      width: 100%;
      height: 100%;
      background: unset;
      border: 0;
      // height: 18px;
      // width: 192px;
      display: flex !important;
    }
    .upload-img {
      height: 180px;
      width: 200px;
    }
    .ant-upload-list-picture-card-container,
    .ant-upload-list-item {
      height: 188px;
      width: 192px;
    }
    .ant-upload-select-picture-card {
      background: url('../../../../assets/imgs/upload-img-bg.png') no-repeat;
      background-size: 100% 100%;
    }
    .ant-upload-list-item {
      border: 1px solid #0855cc;
    }
  }
  .form-table-style {
    /deep/.ant-form-item-label {
      background: #084dbe;
      border: 1px solid #0855cc;
      padding-left: 12px;
      height: 100%;
      flex-shrink: 0;
      > label {
        font-weight: 500;
        font-size: 14px;
        color: #8fbbff;
      }
    }
    /deep/.ant-form-explain {
      position: absolute;
      z-index: 10;
      bottom: -5px;
      left: 10px;
    }
    /deep/.ant-form-item-control-wrapper {
      flex: 1;
      height: 100%;
    }
    /deep/.ant-form-item {
      align-items: stretch;
      margin-right: 0;
      height: 46px;
      display: flex;
    }
    /deep/.ant-form-item-with-help {
      margin-right: 0;
      margin-bottom: 0;
    }
    /deep/.ant-form-item-control {
      height: 100%;
      .ant-form-item-children {
        height: 100%;
        display: block;
        .ant-input {
          height: 100%;
          background: #07429e;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          color: #fff;
          &::placeholder {
            color: #6ea7ff;
          }
        }
        .ant-select {
          height: 100%;
          vertical-align: top;
        }

        .ant-calendar-picker {
          height: 100%;
          > div {
            height: 100%;
          }
        }
        .ant-select-selection {
          height: 100%;
          background: #0a49af;
          border: 0;
          border-radius: 0;
        }
        .select-jurisdiction {
          width: 339px;
        }

        .ant-select-selection__rendered {
          height: 100%;
        }
        .ant-select-selection-selected-value {
          line-height: 42px;
          color: #fff;
        }
        .ant-select-selection__placeholder {
          color: #6ea7ff;
        }
      }
    }
    .right-box-width {
      max-width: 480px;
    }
  }
}

.imageUpload {
  margin-bottom: 150px;
  /deep/.avatar-uploader {
    > .ant-upload {
      width: 150px;
      height: 176px;
      background: var(--theme-input-bg);
      border: 1px solid var(--theme-input-border);
    }
  }

  /deep/.ant-upload-select-picture-card {
    width: 150px;
    height: 176px;
  }

  /deep/ .ant-upload-list-item {
    width: 150px;
    height: 176px;
  }

  .imgText {
    color: #1163b8;
    font-weight: 500;
  }

  .pictIcon {
    margin-bottom: 10px;
    width: 42px;
    height: 38px;
  }
}
</style>
